package j.quartz.ui.controller.sys.user;

import javax.servlet.http.HttpServletRequest;

import org.apache.shiro.SecurityUtils;
import org.apache.shiro.UnavailableSecurityManagerException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.InvalidSessionException;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import j.quartz.sys.user.SysUserService;
import j.quartz.ui.sys.shiro.realm.SysUserRealm.Principal;

@RequestMapping("/user")
@Controller
public class LoginController {
	
	
	@Autowired
	private SysUserService sysUserService ;
	
	@RequestMapping("/toLogin")
	public ModelAndView toLogin(HttpServletRequest req) {
		ModelAndView view = new ModelAndView() ;
		
		Principal principal = getPrincipal() ;
		if (principal != null && !principal.isMobileLogin()) {
			return new ModelAndView("redirect:/admin");
		}
		
		view.setViewName("/sys/login");
		
		return view;
	}
	
	@RequestMapping(value="/login",method=RequestMethod.POST)
	@ResponseBody
    public String login(String username, String password,String vcode,Boolean rememberMe){
        System.out.println(username);
        System.out.println(vcode);
        UsernamePasswordToken token = new UsernamePasswordToken(
        		username, password/*, false, "127.0.0.1", vcode, false*/);
        SecurityUtils.getSubject().login(token);

        return "loginSuccess";
    }
	
/*	@GetMapping("/login")
	public String login(Model model ,HttpServletRequest req) {
		String username = req.getParameter("username") ;
		String password = req.getParameter("password") ;
		
		String uuid = username ;
		SysUser sysUser = sysUserService.getSysUserByUuid(uuid);
		model.addAttribute("sysUser",sysUser) ;
		
		return ("redirect:/index") ;
	}*/
	
	
	/**
	 * 获取当前登录者对象
	 */
	public static Principal getPrincipal() {
		try {
			Subject subject = SecurityUtils.getSubject();
			Principal principal = (Principal) subject.getPrincipal();
			if (principal != null) {
				return principal;
			}
			// subject.logout();
		} catch (UnavailableSecurityManagerException e) {

		} catch (InvalidSessionException e) {

		}
		return null;
	}
	
	

}
